package dao

import (
	"blog/models"
	"database/sql"
	"html/template"
	"log"
)

func CountGetAllPost() (count int, err error) {
	// row := DB.QueryRow("select count(1) from blog_post")
	// err = row.Scan(&count)
	// if err != nil {
	// 	log.Println("CountGetAllPost查询失败", err)
	// 	return 0, err
	// }
	return GetCount("blog_post")
}

func CountGetAllPostBySlug(slug string) (count int, err error) {
	// row := DB.QueryRow("select count(1) from blog_post where slug =?", slug)
	// err = row.Scan(&count)
	// if err != nil {
	// 	log.Println("CountGetAllPost查询失败", err)
	// 	return 0, err
	// }
	return GetCountAndWhere("blog_post", "where slug =?", slug)
}

func CountGetPostByCategoryId(cId int) (count int, err error) {
	row := DB.QueryRow("select count(1) from blog_post where category_id = ?", cId)
	err = row.Scan(&count)
	if err != nil {
		log.Println("CountGetPostByCategoryId查询失败", err)
		return 0, err
	}
	return count, err
}

func GetPostMorePage(page, pageSize int) ([]models.PostMore, error) {
	page = (page - 1) * pageSize
	rows, err := DB.Query("select * from blog_post limit ? , ?", page, pageSize)
	if err != nil {
		log.Println("GetPostMorePage查询失败", err)
		return nil, err
	}
	return getPostMoreByRows(rows)
}
func GetPostMorePageBySlug(slug string, page, pageSize int) ([]models.PostMore, error) {
	page = (page - 1) * pageSize
	rows, err := DB.Query("select * from blog_post where slug =?  limit ? , ?", slug, page, pageSize)
	if err != nil {
		log.Println("GetPostMorePage查询失败", err)
		return nil, err
	}
	return getPostMoreByRows(rows)
}

func GetPostPageByCategoryId(cId, page, pageSize int) ([]models.PostMore, error) {
	page = (page - 1) * pageSize
	rows, err := DB.Query("select * from blog_post where category_id = ? limit ? , ?", cId, page, pageSize)
	if err != nil {
		log.Println("GetPostPageByCategoryId查询失败", err)
		return nil, err
	}
	return getPostMoreByRows(rows)
}

func getPostMoreByRows(rows *sql.Rows) ([]models.PostMore, error) {
	var posts []models.Post
	for rows.Next() {
		var post models.Post
		err := rows.Scan(
			&post.Pid,
			&post.Title,
			&post.Content,
			&post.Markdown,
			&post.CategoryId,
			&post.UserId,
			&post.ViewCount,
			&post.Type,
			&post.Slug,
			&post.CreateAt,
			&post.UpdateAt,
		)
		if err != nil {
			log.Println("getPostByRows取值失败", err)
			return nil, err
		}
		posts = append(posts, post)
	}
	var postMores []models.PostMore

	for _, post := range posts {
		categoryName, err := GetCategoryNameById(post.CategoryId)
		if err != nil {
			log.Println("GetCategoryNameById取值失败", err)
			return nil, err
		}
		userName, err := GetUserNameById(post.UserId)
		if err != nil {
			log.Println("GetUserNameById取值失败", err)
			return nil, err
		}
		postMore := buildPostMore(post, categoryName, userName, true)
		postMores = append(postMores, postMore)
	}
	return postMores, nil
}

func GetPostMoreByPId(pId int) (models.PostMore, error) {
	row := DB.QueryRow("select * from blog_post where pid = ? limit 1", pId)
	return getPostMoreByRow(row)
}
func GetPostById(pId int) (models.Post, error) {
	row := DB.QueryRow("select * from blog_post where pid = ? limit 1", pId)
	return buildPost(row)
}

func getPostMoreByRow(rows *sql.Row) (postMore models.PostMore, err error) {
	var post models.Post
	post, err = buildPost(rows)
	if err != nil {
		log.Println("getPostByRow取值失败", err)
		return postMore, err
	}

	categoryName, err := GetCategoryNameById(post.CategoryId)
	if err != nil {
		log.Println("GetCategoryNameById取值失败", err)
		return postMore, err
	}
	userName, err := GetUserNameById(post.UserId)
	if err != nil {
		log.Println("GetUserNameById取值失败", err)
		return postMore, err
	}
	postMore = buildPostMore(post, categoryName, userName, false)
	return postMore, nil
}

func buildPost(rows *sql.Row) (models.Post, error) {
	var post models.Post
	err := rows.Scan(
		&post.Pid,
		&post.Title,
		&post.Content,
		&post.Markdown,
		&post.CategoryId,
		&post.UserId,
		&post.ViewCount,
		&post.Type,
		&post.Slug,
		&post.CreateAt,
		&post.UpdateAt,
	)
	if err != nil {
		log.Println("buildPost取值失败", err)
	}
	return post, err
}

func buildPostMore(post models.Post, categoryName string, userName string, isContractions bool) models.PostMore {
	content := []rune(post.Content)
	if isContractions {
		if len(content) > 100 {
			content = content[0:100]
		}
	}
	return models.PostMore{
		Pid:          post.Pid,
		Title:        post.Title,
		Slug:         post.Slug,
		Content:      template.HTML(content),
		CategoryId:   post.CategoryId,
		CategoryName: categoryName,
		UserId:       post.UserId,
		UserName:     userName,
		ViewCount:    post.ViewCount,
		Type:         post.Type,
		CreateAt:     models.DateDay(post.CreateAt),
		UpdateAt:     models.DateDay(post.UpdateAt),
	}
}

func SavePost(post *models.Post) {
	result, err := DB.Exec("insert into blog_post( title, content, markdown, category_id, user_id, view_count, type, slug, create_at,update_at)"+
		"values(?,?,?,?,?,?,?,?,?,?)",
		post.Title, post.Content, post.Markdown, post.CategoryId, post.UserId, post.ViewCount, post.Type, post.Slug, post.CreateAt, post.UpdateAt)
	if err != nil {
		log.Println(err)
	}
	pid, _ := result.LastInsertId()
	post.Pid = int(pid)
}
func UpdatePost(post *models.Post) {
	_, err := DB.Exec("update blog_post set title=?, content=?, markdown=?, category_id=?, type=?, slug=?, update_at=? where pid = ?",
		post.Title, post.Content, post.Markdown, post.CategoryId, post.Type, post.Slug, post.UpdateAt, post.Pid)
	if err != nil {
		log.Println(err)
	}
}

func GetPostAll() ([]models.Post, error) {
	// rows, err := DB.Query("select * from blog_post")
	// if err != nil {
	// 	log.Println(err)
	// }
	return GetList[models.Post]("select * from blog_post")
}

func getPostByRows(rows *sql.Rows) ([]models.Post, error) {
	var posts []models.Post
	for rows.Next() {
		var post models.Post
		err := rows.Scan(
			&post.Pid,
			&post.Title,
			&post.Content,
			&post.Markdown,
			&post.CategoryId,
			&post.UserId,
			&post.ViewCount,
			&post.Type,
			&post.Slug,
			&post.CreateAt,
			&post.UpdateAt,
		)
		if err != nil {
			log.Println("getPostByRows取值失败", err)
			return nil, err
		}
		posts = append(posts, post)
	}
	return posts, nil
}

func IncrementPostViewCountByPId(pId int) {
	_, err := DB.Exec("update blog_post set view_count=view_count+1 where pId = ?", pId)
	if err != nil {
		log.Println(err)
	}
}

func GetPostSearch(condition string) ([]models.Post, error) {
	// rows, err := DB.Query("select * from blog_post where title like ?", "%"+condition+"%")
	// if err != nil {
	// 	log.Println(err)
	// }
	p, err2 := GetList[models.Post]("select * from blog_post where title like ?", "%"+condition+"%")
	//return getPostByRows(rows)
	return p, err2
}
